package cn.luncene;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;

/**
 * @author Administrator
 * @Title: 萧萧
 * @ProjectName lucene
 * @Description: 使用queryparser查询
 * @date 2018/9/29 20:52
 */
public class QueryParserTest {
    @Test
    public void test() throws Exception{
        Directory directory = FSDirectory.open(new File("I:\\视频\\lucene学生\\02.参考资料\\index").toPath());
        IndexReader indexReader = DirectoryReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        //创建queryparser对象
        //第一个参数默认搜索的域
        //第二个参数就是分析器对象
        QueryParser queryParser = new QueryParser("content",new IKAnalyzer());
        Query query = queryParser.parse("Lucene是java开发的");

        TopDocs topDocs = indexSearcher.search(query,10);
        System.out.println("总共的记录数为: "+topDocs.totalHits);

        for(ScoreDoc scoreDoc:topDocs.scoreDocs){
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.println(document.get("content"));
            System.out.println(document.get("size"));
            System.out.println(document.get("name"));
        }
        indexReader.close();
    }
}
